<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>history</title>
  </title>
</head>

<body>
  <div>
    <div class="nav">
      <button data-path="/home">首页</button>
      <button data-path="/center">我的</button>
      <button data-path="/hot">热门</button>
    </div>
    <!-- 路由展示容器 -->
    <div id="view"></div>
  </div>
  <script>
    // 定义路由表
    const routes = [
      { path: "/home", content: "Home" },
      { path: "/center", content: "Center" },
      { path: "/hot", content: "Hot" },
    ];
    // 获取元素
    const oNav = document.querySelector(".nav");
    const oView = document.querySelector("#view");
    // 事件委托绑定路由导航
    oNav.onclick = function (e) {
      if ((e.target.nodeName = "BUTTON")) {
        // 得到导航按钮上的路径属性，并通过 history.pushState 修改路径（不会触发浏览器刷新）
        history.pushState(null, null, e.target.dataset.path)
        routes.forEach((route) => {
          if (route.path === location.pathname) {
            oView.innerHTML = route.content;
          }
        });
      }
    };
    // 使用 onhashchange 监听浏览器前进后退的回调的变化
    onpopstate = function (e) {
      console.log(e)
      routes.forEach((route) => {
        if (route.path === location.pathname) {
          oView.innerHTML = route.content;
        }
      });
    };
  </script>
</body>

</html>